package bday.tvlport.scheduler;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import bday.tvlport.utils.LoggerUtility;

public class ApplicationStartup implements ServletContextListener {
	private static String mailCopy;
	private static String mailSupport;
	private Scheduler mailScheduler;
	/**
	 * @see javax.servlet.ServletContextListener#void
	 *      (javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
		try {
			if(getMailScheduler() != null) {
				getMailScheduler().shutdown(true);
			}
		} catch (SchedulerException e) {
			LoggerUtility.error(e.toString());
		}
		LoggerUtility.info("THE APPLICATION STOPPED");
	}

	/**
	 * @see javax.servlet.ServletContextListener#void
	 *      (javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent event) {
		LoggerUtility.info("THE APPLICATION STARTED");
		ServletContext servletContext = event.getServletContext();
		String[] mailTime = servletContext.getInitParameter("mailTime").split(":");
		mailCopy = servletContext.getInitParameter("mailCopy");
		mailSupport = servletContext.getInitParameter("mailSupport");
		try {
			// Initiate a Schedule Factory
			SchedulerFactory schedulerFactory = new StdSchedulerFactory();
			// Retrieve a scheduler from schedule factory
			//Scheduler sortScheduler = schedulerFactory.getScheduler();
			setMailScheduler(schedulerFactory.getScheduler());

			JobDetail mailJob = JobBuilder.newJob(MailingJob.class)
					.withIdentity("mailJob", "group2").build();
			// Initiate SimpleTrigger with its name and group name
			Trigger mailTrigger = TriggerBuilder
					.newTrigger()
					.withIdentity("mailTrigger", "group2")
					.withSchedule(
							CronScheduleBuilder.dailyAtHourAndMinute(Integer.valueOf(mailTime[0]), Integer.valueOf(mailTime[1])))
					.build();
			
			getMailScheduler().scheduleJob(mailJob, mailTrigger);
			getMailScheduler().start();

		} catch (Exception e) {
			LoggerUtility.error(e.toString());
		}
	}

	public static String getMailCopy() {
		return mailCopy;
	}

	public static String getMailSupport() {
		return mailSupport;
	}

	public Scheduler getMailScheduler() {
		return mailScheduler;
	}

	public void setMailScheduler(Scheduler mailScheduler) {
		this.mailScheduler = mailScheduler;
	}
}
